# PySide has no widget for Toggle Buttons. Instead, we use Push buttons in a special mode for this purpose.
# In this program we will change the background color of a frame based on selection by toggle buttons.
# For changing color, css property 'background-color: xxx' is used

import sys
from PySide import QtGui, QtCore


class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()

        # Default background color
        self.col = QtGui.QColor(0, 0, 0)
        print(self.col.name)

        # Frame of which the background-color will be changed
        self.frame = QtGui.QFrame(self)
        self.frame.setGeometry(100, 20, 100, 100)
        self.frame.setStyleSheet("QWidget {background-color: %s}" % self.col.name())

        redBtn = QtGui.QPushButton("Red", self)
        # To create a ToggleButton, we create a QtGui.QPushButton and make it checkable by calling the
        # setCheckable() method.
        redBtn.setCheckable(True)
        redBtn.move(20, 20)
        # We connect a clicked[bool] signal to our user defined method. Note that this signal type sends a bool
        # argument to the method. The argument value is true or false, depending on the state of the button,
        # e.g. if it is checked/toggled or not.
        redBtn.clicked[bool].connect(self.changeFrameColor)

        grnBtn = QtGui.QPushButton("Green", self)
        grnBtn.setCheckable(True)
        grnBtn.move(20, 50)
        grnBtn.clicked[bool].connect(self.changeFrameColor)

        bluBtn = QtGui.QPushButton("Blue", self)
        bluBtn.setCheckable(True)
        bluBtn.move(20, 80)
        bluBtn.clicked[bool].connect(self.changeFrameColor)

        self.setGeometry(200, 200, 250, 200)
        self.setWindowTitle("Toggle Buttons")

    def changeFrameColor(self, pressed):
        source = self.sender()
        if pressed:
            val = 255
        else:
            val = 0
        # The .text() property is not found by auto complete.
        if source.text() == "Red":
            self.col.setRed(val)    # setRed, setGreen and setBlue functions are new to me
        if source.text() == "Green":
            self.col.setGreen(val)
        if source.text() == "Blue":
            self.col.setBlue(val)

        self.frame.setStyleSheet("QFrame { background-color: %s }" % self.col.name())

if __name__ == "__main__":
    appObject = QtGui.QApplication(sys.argv)
    ex = Window()
    ex.show()
    sys.exit(appObject.exec_())

